import { ref, reactive } from 'vue'
import app from '@/app'
import store from '@/app/store'
import { get } from '@/api/erp/inbound'

// 初始化
const inboundStore = store()

// 分页
inboundStore.page = reactive({
  current: 1,
  pageSize: 0,
  total: 0,
  pageSizeOptions: [10, 20, 50, 100],
  loading: false
})

// 查询类型
inboundStore.where = reactive({ 
  key: 'code', 
  value: '',
  time: []
})

// 生成查询数据
inboundStore.getWhere = () => {
  // 查询方式
  const where = { 
    [inboundStore.where.key]: inboundStore.where.value,
    time: inboundStore.where.time
  }
  // 合并数据
  return Object.assign(where, inboundStore.getData())
}

inboundStore.get = () => {
  return new Promise((resolve, jeject) => {
    inboundStore.page.loading = true
    get(inboundStore.getWhere()).then(res => {
      const list = res.data.map((item, index) => {
        item.created_at = app.time.load(item.created_at)
        return item
      })
      inboundStore.setList(list)
      // 分页
      inboundStore.page.current = res.current_page
      inboundStore.page.pageSize = res.per_page
      inboundStore.page.total = res.total
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      inboundStore.page.loading = false
    })
  })
}

// 重置请求
inboundStore.reset = (page, size) => {
  inboundStore.page.current = page
  inboundStore.page.pageSize = size
  inboundStore.getData().page = page
  inboundStore.getData().page_size = size

  // 开始加载
  inboundStore.get()
}

export default inboundStore